package com.czy.owner.ui.information;

import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.czy.owner.R;
import com.czy.owner.api.CollectionApi;
import com.czy.owner.api.OwnerInfoIsCollectApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.hotshop.GoodsDetailActivity;
import com.czy.owner.utils.AssetsFileUtils;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.ShareUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.google.gson.JsonObject;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import butterknife.BindView;

/**
 * Created by wangyang on 2017/5/16 0016.
 * 汽车资讯详情
 */

public class InformationDetailActivity extends BaseActivity {
    @BindView(R.id.webview)
    WebView webView;
    @BindView(R.id.myProgressBar)
    ProgressBar myProgressBar;
    private String title;
    private String content;
    private String imgUrl;
    private int infoId;
    private String collectType;
    private boolean mIsCollect;

    MenuItem itemCollect;
    private String url;
    private String postDate;
    private String session;
    private String shareUrl;
    private int storeId;


    //    单独处理首页攻略收藏
    private int position;
    private String mType = "listStrategy";

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_webview;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        title = getIntent().getStringExtra("title");
        content = getIntent().getStringExtra("content");
        imgUrl = getIntent().getStringExtra("imgUrl");
        infoId = getIntent().getIntExtra("infoId", 0);
        collectType = getIntent().getStringExtra("collectType");
        MyLog.e("yang","collectType=="+collectType);
//        isCollect = getIntent().getBooleanExtra("isCollect", false);
        mType = getIntent().getStringExtra("mType");
        session = UserHelper.getInstance().getSession(InformationDetailActivity.this);
        storeId = (int) SharedPreferencesUtils.getParam(InformationDetailActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0);
        if (collectType.equals("activity")) {
            url = Constants.APP_API_BASE + Constants.OWN_INFO_ACTIVITY;
            getToolbarTitle().setText("活动详情");
        } else if (collectType.equals("caseShow")) {
            url = Constants.APP_API_BASE + Constants.OWN_CASESHOWS;
            getToolbarTitle().setText("案例展示详情");
        } else if (collectType.equals("storeActivity")) {
            url = Constants.APP_API_BASE + Constants.OWN_STORE_ACTIVITY_DETAIL;
            getToolbarTitle().setText("活动详情");
        } else {
            url = Constants.APP_API_BASE + Constants.OWN_INFO_INFOCONTENT;
            if (collectType.equals("strategy")) {
                getToolbarTitle().setText("攻略详情");
                position = getIntent().getIntExtra("position", -1);
            } else if (collectType.equals("headlines")) {
                getToolbarTitle().setText("袋鼠头条详情");
            } else {
                getToolbarTitle().setText("资讯详情");
            }


        }
        WebSettings ws = webView.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setUseWideViewPort(false);  //将图片调整到适合webview的大小
        ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        if (collectType.equals("activity")) {
            postDate = "session=" + session + "&activityId=" + infoId;
        } else if (collectType.equals("storeActivity")) {
            postDate = "session=" + session + "&storeId=" + storeId + "&activityId=" + infoId;
        } else {
            postDate = "session=" + session + "&infoId=" + infoId;
        }
        webView.postUrl(url, postDate.getBytes());

        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    myProgressBar.setVisibility(View.GONE);
                } else {
                    if (View.GONE == myProgressBar.getVisibility()) {
                        myProgressBar.setVisibility(View.VISIBLE);
                    }
                    myProgressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }


        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                MyLog.d("yang",request.getUrl().toString());
                Pattern p = Pattern.compile("pub/goodsView\\?goodsId=(\\d*?)$");
                Matcher m = p.matcher(request.getUrl().toString());
                while (m.find()) {
                    final String goodsId = m.group(1);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            webView.stopLoading();
                            webView.postUrl(url, postDate.getBytes());
                            Intent intent = new Intent(InformationDetailActivity.this, GoodsDetailActivity.class);
                            intent.putExtra("goodsId", Integer.parseInt(goodsId));
                            MyLog.d("yang","goodsId=="+goodsId);
                            intent.putExtra("mFromType", Constants.GOODSSOURCE_STRATEGY);
//                            if(collectType.equals("strategy")){
                                intent.putExtra("mFromTypeId", infoId+"");
//                            }else {
//                                intent.putExtra("mFromTypeId", "0");
//                            }

                            startActivity(intent);
                        }
                    });
                    return null;
                }
                return super.shouldInterceptRequest(view, request);
            }

        });

    }


    public void ownerInfoIsCollect(String type) {
        OwnerInfoIsCollectApi ownerInfoIsCollectApi = new OwnerInfoIsCollectApi(new HttpOnNextListener<JsonObject>() {
            @Override
            public void onNext(JsonObject result) {
                boolean isCollect = JsonUtil.getJsonValuesBoolean(result.toString(),"isCollect");
                mIsCollect = isCollect;
                MyLog.e("yang","mIsCollect=="+mIsCollect);
                if (mIsCollect) {
                    itemCollect.setIcon(R.mipmap.icon_webview_collection_select);
                } else {
                    itemCollect.setIcon(R.mipmap.icon_webview_collection_normal);
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(InformationDetailActivity.this, e.getMessage());
            }
        }, InformationDetailActivity.this);

        ownerInfoIsCollectApi.setSession(session);
        ownerInfoIsCollectApi.setInfoId(infoId + "");
        ownerInfoIsCollectApi.setType(type);
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(ownerInfoIsCollectApi);
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_information_detail_top, menu);
        itemCollect = menu.findItem(R.id.img_collection);

        if (collectType.equals("activity") || collectType.equals("storeActivity") || collectType.equals("caseShow") || collectType.equals("headlines")) {
            itemCollect.setVisible(false);
        }else {
            if (UserHelper.getInstance().isLogined()) {
                ownerInfoIsCollect(collectType);
            }

        }


//        if (isCollect) {
//            itemCollect.setIcon(R.mipmap.icon_webview_collection_select);
//        } else {
//            itemCollect.setIcon(R.mipmap.icon_webview_collection_normal);
//        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.icon_share:
                if (TextUtils.isEmpty(imgUrl)) {
                    try {
                        AssetsFileUtils.getImageFromAssetsFile(InformationDetailActivity.this, "owner_share_icon.png");
                    } catch (Exception e) {

                    }
                }
                if (collectType.equals("activity") || collectType.equals("storeActivity")) {
                    shareUrl = Constants.APP_API_BASE + Constants.STO_ACTIVITY_SHARE + "?activityId=" + infoId;
                } else if(collectType.equals("caseShow")){
                    shareUrl = Constants.APP_API_BASE + Constants.STO_INTO_CASE_SHARE + "?infoId=" + infoId;
                }else {
                    shareUrl = Constants.APP_API_BASE + Constants.STO_INTO_SHARE + "?infoId=" + infoId;
                }
                ShareUtils.showShare(this, null, false, shareUrl, PhoneUtils.delHTMLTag(title), PhoneUtils.delHTMLTag(content), imgUrl, shareUrl);
                break;
            case R.id.img_collection:
                if (checkLoginState()) {
                    if (mIsCollect) {
                        requestCollect(collectType, infoId + "", "delCollect", false);
                        itemCollect.setIcon(R.mipmap.icon_webview_collection_normal);
                    } else {
                        requestCollect(collectType, infoId + "", "", true);
                        itemCollect.setIcon(R.mipmap.icon_webview_collection_select);
                    }
                }
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.destroy();
    }

    private void requestCollect(final String collectType, String collectTypeId, String type, final boolean isMCollect) {
        CollectionApi collectionApi = new CollectionApi(new HttpOnNextListener<String>() {
            @Override
            public void onNext(String o) {
                if (isMCollect) {
                    PhoneUtils.ShowToastMessage(InformationDetailActivity.this, "收藏成功");
                    mIsCollect = true;

                } else {
                    PhoneUtils.ShowToastMessage(InformationDetailActivity.this, "取消成功");
                    mIsCollect = false;

                }
                RxBus.getDefault().post(Constants.COLLECTION, new CommonEvent(collectType));


            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(InformationDetailActivity.this, e.getMessage());
            }
        }, this);
        collectionApi.setSession(UserHelper.getInstance().getSessionInfoModel(InformationDetailActivity.this).getSession());
        collectionApi.setCollectType(collectType);
        collectionApi.setCollectTypeId(collectTypeId);
        collectionApi.setType(type);
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(collectionApi);


    }


}
